// tickets/process/process.js 
var app = getApp();
let get = (op = { login: false }) => { //这边的options就是get括号里面的对象  这个返回的是数据

  if (!op.isShowLoading) {

    wx.showNavigationBarLoading()
  }
  if (op.data && op.data.hasOwnProperty("token")) {
    op.data.token = wx.getStorageSync("token") || '';
  }

  if (!op.header) {
    op.header = {
      loginType: platform.loginType
    }
  } else {
    op.header.loginType = platform.loginType;
    if (op.header.hasOwnProperty("token")) {
      op.header.token = wx.getStorageSync("token") || '';
    }
  }
  if (!op.hasOwnProperty('login')) {
    op.login = false;
  }
  op.header.ext = wx.getStorageSync("ext") || '';
  let obj = {
    ...op,
    method: 'GET'
  };
  console.log("api-req:", obj);
  return api.request(obj).then((res) => {
    // 成功回调
    console.log("api-res:", res);
    if (!op.isShowLoading) {
      wx.hideNavigationBarLoading()
    }
    // 票据录入和发票抬头信息
    if (res.statusCode == 200) {
      if (res.data.code == 10000 || res.data.code == 200 || res.data.statusCode == 200) {
      } else {
        if (res.data.code == 10002 || res.data.statusCode == 2) { //绑定手机号
          if (op.login) {
            wx.showModal({
              title: '提示',
              content: '服务器繁忙，请稍后重试'
            })
            return;
          }
          app.login(get, op);
        } else {
          res.data.message && res.data.message != "未设置默认企业发票抬头" && wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
      return res.data
    } else if (res.statusCode == 500) {
      if (res.data.message) {
        wx.showToast({
          title: "状态为:" + res.data.message,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: "状态为:" + res.statusCode,
          icon: 'none'
        })
      }
    } else if (res.statusCode == 502) {
      if (res.data.message) {
        wx.showToast({
          title: "状态为:" + res.data.message,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: "状态为:" + res.statusCode,
          icon: 'none'
        })
      }
    } else {
      console.error("get", res);
    }
  }, (res) => {
    if (res.errMsg) {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
    }
  })
}
let post = (op = {}) => {
  wx.showNavigationBarLoading()
  if (!op.header) {
    op.header = {
      loginType: platform.loginType
    }
  } else {
    op.header.loginType = platform.loginType;
    if (op.header.hasOwnProperty("token")) {
      op.header.token = wx.getStorageSync("token") || '';
    }
  }
  op.header.ext = wx.getStorageSync("ext") || '';
  if (!op.hasOwnProperty('login')) {
    op.login = false;
  }
  console.log("api-req:", {
    ...op,
    header: {
      'content-type': 'application/json',
      ...op.header
    },
    method: 'POST'
  });
  return api.request({
    ...op,
    header: {
      'content-type': 'application/json',
      ...op.header
    },
    method: 'POST'
  }).then((res) => {
    console.log("api-res:", res);
    wx.hideNavigationBarLoading()
    if (res.statusCode == 200) {
      if (res.data.code == 10000 || res.data.code == 200 || res.data.statusCode == 200) {
      } else {
        if (res.data.code == 10002 || res.data.statusCode == 2) { //绑定手机号
          if (op.login) {
            wx.showModal({
              title: '提示',
              content: '服务器繁忙，请稍后重试'
            })
            return;
          }
          app.login(get, op);
        } else {
          res.data.message && wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
      return res.data
    } else if (res.statusCode == 500) {
      if (res.data.message) {
        wx.showToast({
          title: "状态为:" + res.data.message,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: "状态为:" + res.statusCode,
          icon: 'none'
        })
      }
    } else if (res.statusCode == 502) {
      if (res.data.message) {
        wx.showToast({
          title: "状态为:" + res.data.message,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: "状态为:" + res.statusCode,
          icon: 'none'
        })
      }
    } else {
    }
  }, (res) => {
    if (res.errMsg) {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
    }
  });
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,//百分比动画展示
    tempFilePaths: '',
    ocrType: '',
    showLogin: false,//登录
    isKg: false,//设置开关
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { tempFilePaths, ocrType, } = options;
    this.setData({
      tempFilePaths,
      ocrType,
    })
    console.log('识别中tempFilePaths', tempFilePaths)
  },
  // 调阿里云接口
  GetOSSPolicy: function (token, tempFilePaths, ocrType) {

    console.log('调阿里云接口host1', new Date().getTime())
    var that = this;
    that.percentDH(20)
    return get({
      url: api.pathName_node + "utils/getOSSPolicy",
      data: {
        token,
        loginType: platform.loginType
      },
      isShowLoading:false
    }).then(res => {
      console.log('调阿里云接口host2', new Date().getTime())
      if (res.code == 10000) {
        let { OSSAccessKeyId, Signature, callback, host, key, policy, success_action_status } = res.data.formData;
        console.log('getOSSPolicy 10000')
        console.log('wx.uploadFile1', new Date().getTime())
        wx.uploadFile({
          url: host,
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            'key': key,
            'OSSAccessKeyId': OSSAccessKeyId,
            'policy': policy,
            'Signature': Signature,
            'success_action_status': success_action_status,
            'callback': callback
          },
          success: function (res) {
            console.log('wx.uploadFile2-70', new Date().getTime())
            that.percentDH(70)
            if (res.statusCode == 200) {
              var imageUrl = JSON.parse(res.data).url
              console.log(res, 'wx.uploadFile1')
              console.log(token, 'token')
              // 得到图片路劲
              wx.uploadFile({
                url: api.pathName_node + "ocr/ocrMulti" + `?token=${token}`,
                filePath: tempFilePaths,
                name: 'file',
                formData: {
                  // "ocrType": ocrType,
                  "imageUrl": imageUrl
                },
                success: function (res) {
                  console.log('wx.uploadFile4-90', new Date().getTime())
                  that.percentDH(90)
                  if (res.statusCode == 200) {
                    var data = JSON.parse(res.data)
                    console.log('res2222222222222', data)
                    if (data.code == 10000) {
                      wx.setStorageSync('ocrDetailLists', data.data)
                      that.percentDH(100, function () {
                        wx.redirectTo({
                          url: '/tickets/ocrDiscern/ocrDiscern',
                        })
                      })
                    } else {//ocr票据录入失败
                      that.percentDH(100, function () {
                        wx.redirectTo({
                          url: `/tickets/failInfo/failInfo?message=${data.message}`
                        })
                        return;
                      })
                    }
                  } else {
                    wx.reLaunch({
                      url: `/pages/home/home`,
                      success: function () {
                        wx.showToast({ title: "上传错误", icon: 'none' })
                      }
                    })
                    return;
                  }
                },
                fail: function (e) {
                  console.log(e);
                },
              })
            } else {
              console.log('uploadFile 1 fail')
              wx.reLaunch({
                url: "/pages/home/home",
                success: function () {
                  wx.showToast({ title: res.statusCode.toString() + "上传错误", icon: 'none' })
                }
              })
              return;
            }
          },
          fail: function (res) {
            wx.reLaunch({
              url: "/pages/home/home",
              success: function () {
                wx.showToast({ title: "上传错误", icon: 'none' })
              }
            })
            return;
          }
        })

      } else {
        wx.reLaunch({
          url: "/pages/home/home",
          success: function () {
            wx.showToast({ title: "上传错误", icon: 'none' })
          }
        })
        return;
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let _this = this;
    if (!this.data.isKg) {
      _this.getInfo()
    }

  },
  onHide: function () {
    if (!this.data.isKg) {
      this.data.isKg = true;
    }
  },
  onShow: function () {
    if (this.data.isKg) {
      this.getInfo()
    }

    console.log('识别 show')
  },
  //百分比动画展示
  percentDH(b, callback) {//b百分比后一个
    let _this = this;
    let loop = b - this.data.percent
    let speed = parseInt(loop) < 10 ? parseInt(loop) * 2 : parseInt(loop)
    // console.log(this.data.percent)
    if (this.data.percent + 1 >= b) {
      this.setData({
        percent: b
      })
      if (this.data.percent == 100) {
        callback && callback()
      }
    } else {
      this.setData({
        percent: this.data.percent + 1
      })
      setTimeout(function () {
        _this.percentDH(b, callback)
      }, speed)
    }
  },
  getInfo: function () {
    var _this = this;
    console.log('检查绑定1', new Date().getTime())
    app.checkToken({
      bind: function () {
        _this.setData({
          showLogin: true,
        })
      },
      all: function (res) {

        _this.setData({
          showLogin: false
        })
        console.log('检查绑定2', new Date().getTime())
        _this.GetOSSPolicy(wx.getStorageSync("token"), _this.data.tempFilePaths, _this.data.ocrType)
      }
    })
  },
  bindBlur() {
    wx.navigateBack({
      delta: 1,
    })
  },
  //绑定成功
  bindSuccess() {
    this.getInfo();

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "数学作业",
      path: '/pages/math/math',
      imageUrl: 'https://dl.cdn.webaozhang.com/wbzfe/190918172535home.png'
    }
  }
})
function toCamel(str) {
  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
}